<?php
$country_ipv4 = file('country-ipv4.lst');
$cn_range = array();
foreach ($country_ipv4 as $k=>$line) {
    if (preg_match('/^([.\\d]+)\\s+-\\s+([.\\d]+)\\s+:\\s+([.\\d]+)\/\d+\\s+:\\s+(\w+)/', $line, $m) && strtolower($m[4]) == 'cn') {
        $cn_range[] = array(
            'begin' => (float)sprintf('%u', ip2long($m[1])),
            'end' => (float)sprintf('%u', ip2long($m[2]))
        );
    }
}

usort($cn_range, create_function('$a,$b', '
    if ($a["begin"] == $a["begin"]) {
        return 0;
    }

    return ($a["begin"] < $b["begin"]) ? -1 : 1;
'));

function cross_detection($range) {
    foreach ($range as $v1) {
        foreach ($range as $v2) {
            if ($v1 == $v2) {
                continue;
            }

            if ($v1['begin'] >= $v2['begin'] && $v1['begin'] <= $v2['end']) {
                printf("Cross detected!\n");
                exit;
            }
            if ($v1['end'] >= $v2['begin'] && $v1['end'] <= $v2['end']) {
                printf("Cross detected!\n");
                exit;
            }
        }
    }
}


function in_range($val, $range) {
    $val = (float)$val;
    foreach ($range as $k=>$v) {
        if ($val >= $v['begin'] && $val <= $v['end']) {
            return true;
        }
    }

    return false;
}

$ip_data = file('ip.txt');
$output = array();
foreach ($ip_data as $k=>$line) {
    if (!($k % 10000)) {
        printf("%d records processing...\n", $k);
    }
    if (preg_match('/([.\\d]+)\s+([.\\d]+)\s+([^\\s]*)/', trim(str_replace('CZ88.NET', '', $line)), $m)) {
        $v1 = ip2long($m[1]);
        $v2 = ip2long($m[2]);
        if (!in_range($v1, $cn_range) && !in_range($v2, $cn_range)) {
            continue;
        }

        $output[] = sprintf('INSERT INTO game_conf.ip_dict (ip1, ip2, str_ip1, str_ip2, `area`) VALUES (%u, %u, \'%s\', \'%s\', \'%s\');',
                          $v1, $v2, $m[1], $m[2], $m[3]);
    }
}

$output = "set names latin1;\n".implode("\n", $output);

file_put_contents('data.sql', iconv("utf8", 'gbk', $output));

printf("OK!\n");
